/**
 * This file is part of AppStoreBot.
 *
 * AppStoreBot is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AppStoreBot is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AppStoreBot.  If not, see <http://www.gnu.org/licenses/>.
 *
 */
package lu.pragmaconsult.appstorebot;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sampullara.cli.Args;

/**
 * 
 * Main class of the Bot.
 * 
 * @author Wilfried Vandenberghe (wilfried.vandenberghe at pragmaconsult.lu)
 */
public class AppStoreBot {

	/**
	 * Logger.
	 */
	private static final Logger logger = LoggerFactory
			.getLogger(AppStoreBot.class);

	/**
	 * 
	 * @param args
	 * @return
	 */
	private BotContext parse(String[] args) {
		BotContext context = new BotContext();
		try {
			List<String> unused = Args.parse(context, args);
			// in case of help or
			if (context.isHelp() || unused.size() > 0) {
				Args.usage(context);
				return null;
			}
		} catch (IllegalArgumentException e) {
			Args.usage(context);
			return null;
		}

		return context;
	}

	/**
	 * Entry point method for application.
	 * 
	 * @param args
	 *            application arguments
	 */
	public static void main(String[] args) {
		AppStoreBot main = new AppStoreBot();
		BotContext context = main.parse(args);

		if (context != null) {
			// create a bot and log error
			Bot bot = null;
			try {
				BotFactory factory = new BotFactory();
				bot = factory.createBot(context);
			} catch (Exception t) {
				logger.error(t.getMessage());
				System.exit(-1);
			}

			// run the bot
			if (bot != null) {
				ExitStatus status = bot.run();
				logger.info(status.getMessage());
				System.exit(status.getReturnCode());
			}
		}
	}

}
